package com.ruoyi.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpHelper;
import com.ruoyi.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Component
public class RemoteInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String nowParams = "";
        if (request instanceof RepeatedlyRequestWrapper) {
            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
            nowParams = HttpHelper.getBodyString(repeatedlyRequest);
        }

        // body参数为空，获取Parameter的数据
        if (StringUtils.isEmpty(nowParams)) {
            nowParams = JSON.toJSONString(request.getParameterMap());
        }
        JSONObject paramJson = JSONObject.parseObject(nowParams);
        String apiVersion = paramJson.getString("apiversion");
        if (StrUtil.isNotBlank(apiVersion)) {
            String sysVersion = redisCache.getCacheObject(CacheConstants.SYS_CONFIG_KEY + "biz.app.version");
            if (!Objects.equals(apiVersion, sysVersion)) {
                throw new ServiceException("当前app版本较低，请更新版本，访问黑龙江省建筑起重机械安全监督管理系统http://111.42.127.152:12003登陆页面扫码下载！");
            }
        }

//        String token = paramJson.getString("token");
//        if (StrUtil.isBlank(token)) {
//            return false;
//        }
//        LoginUser loginUser = tokenService.getAppLoginUser(token);
//        log.info("app user:{},request url:{}", JSON.toJSON(loginUser),request.getPathInfo());
//        if (StringUtils.isNotNull(loginUser)) {
//            tokenService.verifyAppToken(loginUser);
//        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
